import { genStorageKey } from "@/utils/common"
import { atom } from "jotai"
import { atomWithStorage } from "jotai/utils"
import cloneDeep from "lodash/cloneDeep"

/**
 * @description 用户信息初始值，结构需与后端返回保持一致
 */
export const initUserInfo: ApiTypes.Fetcher.Result.UserProfile = {
    avatar: "",
    country_code: "",
    created_at: 0,
    created_ip: "",
    device_number: "",
    email: "",
    email_check_state: 0,
    gender: "",
    hasEmail: false,
    hasLoginPassword: false,
    hasPhoneNumber: false,
    last_login_at: 0,
    last_login_device: 0,
    last_login_ip: "",
    nick_name: "",
    note: "",
    oauth_secrets: "",
    parent_name: "",
    parent_uid: "",
    password: "",
    phone: "",
    phone_check_state: 0,
    referral_code: "",
    reg_device: 0,
    reg_device_no: "",
    reg_ip: "",
    state: 0,
    tags: "",
    tester: 0,
    uid: "",
    updated_at: 0,
    username: "",
    vip: 0,
}

/**
 * @description 用户信息全局状态，使用 localStorage 持久化，刷新页面不丢失
 */
export const userInfoAtom = atomWithStorage<ApiTypes.Fetcher.Result.UserProfile>(
    genStorageKey("user_info"), // localStorage 存储的键名
    cloneDeep(initUserInfo), // 避免引用类型默认值被污染
)

/**
 * @description 用户信息加载状态 atom，可用于加载动画、占位等 UI 控制
 */
export const userInfoLoadingAtom = atom<boolean>(false)

/**
 * @description 记录首页导航切换
 */
export const pagePathAtom = atom<Record<"homeCurrentPath", string>>({
    homeCurrentPath: "",
})
